import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { SupplierEntity } from './supplier.entity'
import { CreateSupplierDto, UpdateSupplierDto } from './dto/supplier.dto'

@Injectable()
export class SupplierService {
  constructor(
    @InjectRepository(SupplierEntity)
    private readonly repo: Repository<SupplierEntity>,
  ) {}

  async page(query: any) {
    const pageNum = Number(query.pageNum || 1)
    const pageSize = Number(query.pageSize || 10)
    const where: any = {}
    if (query.name) where.name = Like(`%${query.name}%`)
    if (query.status !== undefined && query.status !== '') where.status = Number(query.status)

    const [list, total] = await this.repo.findAndCount({
      where,
      order: { supplierId: 'DESC' },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    })
    return { list, total }
  }

  async findOne(id: number) {
    return this.repo.findOne({ where: { supplierId: id } })
  }

  async create(dto: CreateSupplierDto) {
    const exists = await this.repo.findOne({ where: { name: dto.name } })
    if (exists) throw new Error('供应商已存在')
    const entity = this.repo.create(dto as any)
    return this.repo.save(entity)
  }

  async update(id: number, dto: UpdateSupplierDto) {
    await this.repo.update({ supplierId: id }, dto as any)
    return this.findOne(id)
  }

  async remove(ids: number[] | number) {
    const arr = Array.isArray(ids) ? ids : [ids]
    await this.repo.delete(arr)
    return true
  }

  async changeStatus(id: number, status: number) {
    await this.repo.update({ supplierId: id }, { status })
    return this.findOne(id)
  }
}
